<template>
	<view class="uplodaImg">
		<view :class="[{ hasError }]">
			<up-form-item prop="images" ref="itemImgRef">
				<ShmilyDragImage v-model="list" :addImage="addImage" :delImage="delImage" :number="9" />
			</up-form-item>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		toRef,
		inject,
		computed,
		watch,
		nextTick,
	} from 'vue'
	// https://ext.dcloud.net.cn/plugin?id=2393
	import ShmilyDragImage from '@/components/ShmilyDragImage/index.vue'
	import upImgOssHook from '@/components/common/upImgOssHook.js'

	const rules = inject('rules')

	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => {}
		}
	})
	const modelValue = toRef(props, 'modelValue')
	const emit = defineEmits(['update:modelValue'])

	const list = ref([])
	if (modelValue.value.images) list.value = modelValue.value.images.split(',')

	watch(list, (val) => {
		emit('update:modelValue', {
			...props.modelValue,
			images: val && val.length ? val.join(',') : ''
		})
	}, {
		deep: true
	})

	// 通过formItem内部的message来判断当前是不是存在error
	const itemImgRef = ref(null)
	const hasError = computed(() => {
		return itemImgRef?.value?.message
	})

	const addImage = () => {
		wx.chooseMedia({
			count: 6 - list.value.length,
			mediaType: ['image'],
			sourceType: ['album', 'camera'],
			sizeType: ['compressed', 'original'],
			camera: 'back',
			async success(res) {
				uni.showLoading({
					title: '上传中'
				});
				const upImgArr = await upImgOssHook(res.tempFiles).catch(err => {
					console.error(err)
					uni.showToast({
						icon: 'none',
						title: `上传图片错误：${err}`
					})
				})
				uni.hideLoading();

				if (upImgArr && upImgArr.length) {
					list.value.push(...upImgArr.map(item => item.fileKey))
				}
			},
		})
	}
	const delImage = (done) => {
		uni.showModal({
			content: '是否删除?',
			success: (res) => {
				if (res.confirm) {
					// 执行 done() 删除
					done()
				}
			}
		})
	}
</script>

<style lang="scss">
	.uplodaImg {
		padding: 0 30rpx;
		border-radius: 10rpx;
		overflow: hidden;

		>view {
			padding: 19rpx;
			background: #fff;
			border: 1px solid #fff;
		}

		.hasError {
			border: 1px dashed #f56c6c;
		}
	}
</style>